package com.example.jetpackcomposelayouts

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.layout.layout
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.jetpackcomposelayouts.ui.theme.JetpackComposeBasicTheme

/**
 * @author huangzehui
 * @date 1/5/2024 下午6:28 周三
 * @description
 * https://www.bilibili.com/video/BV1ob4y1a7ad?p=18&vd_source=e07cc8cc94eb22bd76722071b03cd199
 */

/**
 * 设置新的文字基线
 *
 * @param firstBaselineToTop 新的文字基线位置
 */
fun Modifier.firstBaselineToTop(firstBaselineToTop: Dp): Modifier {
    return then(
        // 使用 Modifier 的 layout 进行布局
        layout { measurable, constraints ->
            // 测量元素
            val placeable = measurable.measure(constraints = constraints)

            // 测量之后，获取元素的基线值
            val firstBaseline = placeable[FirstBaseline]

            // 元素新的Y坐标 = 新的基线值 - 旧的基线值
            val placeableY = firstBaselineToTop.roundToPx() - firstBaseline

            val height = placeableY + placeable.height

            layout(placeable.width, height) {
                // 设置元素位置
                placeable.placeRelative(0, placeableY)
            }
        }
    )
}

@Composable
fun TextWithPaddingToBaseline() {
    JetpackComposeBasicTheme {
        Text(
            text = "Hi there!",
            Modifier
                .firstBaselineToTop(24.dp)
                .background(Color.Red)
        )
    }
}